package com.chao.webflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.stream.Stream;

@RestController
@Slf4j
public class HelloController {

    @GetMapping("/mono")
    public Mono<String> hello() {
        long start = System.currentTimeMillis();
        // 非阻塞
        Mono<String> stringMono = Mono.fromSupplier(this::getHelloStr);
        log.info("接口耗时：{} 毫秒",System.currentTimeMillis() - start);
        return stringMono;
    }

    private String getHelloStr() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "hello,webflux";
    }

    @GetMapping(value = "/flux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> responseFlux() {
        return Flux.fromStream(Stream.of("spring","mybatis","vue"))
                /**
                 * Schedulers.boundedElastic()是Reactor框架中提供的一种线程池类型，它创建的是一个有界的弹性线程池，适用于I/O任务。该线程池的特点是：
                 * 可重用性：如果线程池中的线程在长时间内都没有被使用，那么将会被回收。
                 * 限制性：有一个最大的线程个数，一般来说是CPU cores x 10
                 */
                .publishOn(Schedulers.boundedElastic())
                .map(s -> {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return "技术栈：" + s;
                });
    }
}
